package com.example.demo.controller;

import Mapper.FoodMapper;
import Mapper.HistoryMapper;
import Mapper.RecordMapper;
import Mapper.UserMapper;
import entity.Food;
import entity.SearchRecord;
import entity.User;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
public class RecordController {

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HistoryMapper historyMapper;


    @PostMapping("/insertrecord")
    @Transactional
    public String insertRecord(@RequestBody SearchRecord record) {
        int userId = record.getUserId();
        System.out.println("客户端传递的 user_id: " + userId);

        User user = userMapper.getUserById(userId);
        if (user == null) {
            System.out.println("用户不存在，user_id: " + userId);
            return "用户不存在，无法插入记录";
        }

        System.out.println(user.getuserid());

        System.out.println("查询到的用户信息: user_id=" + user.getuserid() + ", nickname=" + user.getNickname());

        int nextId = recordMapper.nextId();
        if (nextId == 0) {
            nextId = 1;
        }
        record.setRecordId(nextId); // 确保 record_id 被正确设置
        record.setUserId(userId); // 确保 userId 被正确设置
        recordMapper.insertRecord(record);

        System.out.println("成功插入记录，user_id: " + userId + "，record_id: " + nextId);
        return "插入成功";
    }

    @PostMapping("/getrecord")
    public List<Food> findRecord(int user_id) {
        System.out.println("查询" + user_id + "号的历史记录");
        List<SearchRecord> temp = recordMapper.findRecord(user_id); // 根据用户id查询历史记录

        List<Integer> foodIds = new ArrayList<>();
        for (SearchRecord record : temp) {
            foodIds.add(record.getId()); // 假设 SearchRecord 有一个 getId 方法
        }

        // 确保 foodIds 不为空
        if (foodIds.isEmpty()) {
            return Collections.emptyList();
        }

        List<Food> result = historyMapper.findByIds(foodIds);

        for (SearchRecord record : temp) {
            Food food = result.stream()
                    .filter(f -> f.getId() == record.getId())
                    .findFirst()
                    .orElse(null);
            if (food != null) {
                food.setSearch_time(recordMapper.getRecordTime(record.getRecordId()));
            }
        }
        return result;
    }

    @PostMapping("/deleterecord")
    public String deleteRecord(Integer record_id) {
        recordMapper.deleteRecord(record_id);
        System.out.println("删除"+record_id+"号记录");
        return "删除成功";
    }
}